package com.ruoyi.jiaopei.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.jiaopei.domain.TbKjStudent;
import com.ruoyi.jiaopei.domain.bo.TbClassStudentBo;
import com.ruoyi.jiaopei.domain.bo.TbKjStudentBo;
import com.ruoyi.jiaopei.domain.vo.TbClassStudentVo;
import com.ruoyi.jiaopei.domain.vo.TbClassVo;
import com.ruoyi.jiaopei.domain.vo.TbSortCurriculumVo;
import com.ruoyi.jiaopei.mapper.TbSortCurriculumMapper;
import com.ruoyi.jiaopei.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.jiaopei.domain.bo.TbKjBo;
import com.ruoyi.jiaopei.domain.vo.TbKjVo;
import com.ruoyi.jiaopei.domain.TbKj;
import com.ruoyi.jiaopei.mapper.TbKjMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 课节Service业务层处理
 *
 * @author macy
 * @date 2024-04-03
 */
@RequiredArgsConstructor
@Service
public class TbKjServiceImpl implements ITbKjService {

    private final TbKjMapper baseMapper;
    private final ITbClassStudentService classStudentService;
    private final ITbKjStudentService kjStudentService;

    private final TbSortCurriculumMapper sortCurriculumMapper;

    /**
     * 查询课节
     */
    @Override
    public TbKjVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    @Override
    public Long selectCount(Wrapper<TbKj> queryWrapper){
        return  baseMapper.selectCount(queryWrapper);
    }


    /**
     * 查询课节列表
     */
    @Override
    public TableDataInfo<TbKjVo> queryPageList(TbKjBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TbKj> lqw = buildQueryWrapper(bo);
        Page<TbKjVo> result = baseMapper.selectPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询课节列表
     */
    @Override
    public List<TbKjVo> queryList(TbKjBo bo) {
        LambdaQueryWrapper<TbKj> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TbKj> buildQueryWrapper(TbKjBo bo) {

        QueryWrapper<TbKj> lqw1 = Wrappers.query();
        lqw1.like(StringUtils.isNotBlank(bo.getClassName()),"c.name", bo.getClassName());
        lqw1.like(StringUtils.isNotBlank(bo.getName()),"t.name", bo.getName());

        LambdaQueryWrapper<TbKj> lqw =lqw1.lambda();
        lqw.eq(bo.getClassId() != null, TbKj::getClassId, bo.getClassId());
        lqw.eq(bo.getSortCurriculumId() != null, TbKj::getSortCurriculumId, bo.getSortCurriculumId());
        return lqw;
    }

    /**
     * 新增课节
     */
    @Override
    @Transactional
    public Boolean insertByBo(TbKjBo bo) {
        TbKj add = BeanUtil.toBean(bo, TbKj.class);
        validEntityBeforeSave(add);



        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }

        validEntityAfterSave(add);
        return flag;
    }

    /**
     * 修改课节
     */
    @Transactional
    @Override
    public Boolean updateByBo(TbKjBo bo) {
        TbKj update = BeanUtil.toBean(bo, TbKj.class);
        validEntityBeforeSave(update);
        Boolean res=baseMapper.updateById(update) > 0;
        validEntityAfterSave(update);
        return res;
    }

    /**
     * 保存后的数据校验
     */
    private void validEntityAfterSave(TbKj entity){

        if(entity.getId()!=null){

            TbSortCurriculumVo sortCurriculumVo=sortCurriculumMapper.selectVoById(entity.getSortCurriculumId());
            if(null==sortCurriculumVo){
                throw new ServiceException("排课不存在");
            }

            TbClassStudentBo classStudentBo=new TbClassStudentBo();
            classStudentBo.setClassId(entity.getClassId());
            List<TbClassStudentVo> list=classStudentService.queryList(classStudentBo);
            if(null!=list&&list.size()>0){
                TbKjStudentBo kjStudentBo=null;

                for (int i = 0; i <list.size() ; i++) {

                    long count=kjStudentService.selectCount(new LambdaQueryWrapper<TbKjStudent>()
                        .eq(TbKjStudent::getKjId,entity.getId())
                        .eq(TbKjStudent::getStudentId,list.get(i).getStudentId())
                    );

                    if(count>0){
                        continue;
                    }

                    kjStudentBo=new TbKjStudentBo();
                    kjStudentBo.setCreatedDate(new Date());
                    kjStudentBo.setClassId(entity.getClassId());
                    kjStudentBo.setStudentId(list.get(i).getStudentId());
                    kjStudentBo.setKjId(entity.getId());
                    kjStudentBo.setLessonHours(sortCurriculumVo.getLessonHours());
                    kjStudentBo.setStatus("1");

                    kjStudentService.insertByBo(kjStudentBo);
                }
            }

        }
    }
    private void validEntityBeforeSave(TbKj entity){


    }



    /**
     * 批量删除课节
     */
    @Transactional
    @Override
    public Boolean deleteWithValidByIds(List<Long> ids, Boolean isValid) {
        if(isValid){
            for (int i = 0; i <ids.size() ; i++) {
                long count=kjStudentService.selectCount(new LambdaQueryWrapper<TbKjStudent>()
                    .eq(TbKjStudent::getKjId,ids.get(i))
                );

                if(count>0){
                    throw new ServiceException("课节下还有学员，不能删除。");
                }

            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Transactional
    @Override
    public Boolean refresh(List<Long> ids) {
        for (int i = 0; i <ids.size() ; i++) {
            TbKj kj=baseMapper.selectById(ids.get(i));
            validEntityAfterSave(kj);
        }

        return true;
    }
}
